<?php

class TemplateAction extends CommonAction {

    // 查询数据
    public function index() {
        $this->display();
    }
	public function indexjson() {
        $Template = M("Template");
		$list = $Template->limit(20)->order('id desc')->select();
		$i = 0;
		foreach($list AS $row ){
			$template[$i]['table_id'] = $row['id'];
			$template[$i]['table_name'] = $row['name'];
			$template[$i]['table_value'] = '';
			$template[$i]['table_conf']  = $row['conf'] ? unserialize( $row['conf'] ) : '';
			$template[$i]['table_comments'] = $row['comments'];
			$template[$i]['table_tid'] = $row['id'];
			$i++;
		}
        echo json_encode($template);
    }
	
    // 写入数据
    public function add() {
        $Template = D("Template");		
        if ($vo = $Template->create()) {
            $list = $Template->add();
            if ($list !== false) {
                $this->success('数据保存成功！');
            } else {
                $this->error('数据写入错误！');
            }
        } else {
            $this->error($Template->getError());
        }
    }

    // 更新数据
    public function edit() {
        $Template = D("Template");
        if ($vo = $Template->create()) {
            $list = $Template->save();
            if ($list !== false) {
                $this->success('数据更新成功！');
            } else {
                $this->error("没有更新任何数据!");
            }
        } else {
            $this->error($Template->getError());
        }
    }

    // 删除数据
    public function remove() {
		$id = intval( $_POST['form_id'] );
        if (!empty($id)) {
            $Template = M("Template");
			$vo = $Template->where("id='{$id}'")->find();
            if ($vo) {
				$Template->where("pid='$id'")->delete();
				$result = $Template->delete($id);
				if (false !== $result) {
					$this->success('删除成功！');
				} else {
					$this->error('删除出错！');
				}
			}
        } else {
            $this->error('ID错误！');
        }
    }
	
	public function preview () {
		$id = intval($_GET['form_id']);
		$Template = D('Template');
		if(! empty($id)){
			$tpl = $Template->where("id={$id}")->find();
			echo $Template->getTplValue( @unserialize($tpl['conf']) );
		}else{
			$this->error('ID错误！');
		}
	
	}

}
?>